import React, { Component } from 'react';
import App from 'layout/App.js'
import { FormControl, Button, Table, Pagination, Modal, Radio, Select, Popconfirm, Breadcrumb, Row, Col} from 'tinper-bee';
import { getUseNewTeamReq, getManagerList, getUserBaseDataUrl, searchItemWorkFileList, editWorkFileList, searchPkFromNc, searchWorkProList } from './workarchives.config.js';
import CommonModal from './../../components/CommonModal/index.jsx';
import MapModal from './../../components/ProjectMap/mapModal.jsx';
import ManagerModalContent from './ManagerModalContent.jsx';
import EnterpriseModalContent from './EnterpriseModalContent.jsx';
import MemberModalContent from './MemberModalContent.jsx';
import { vendorsDanger as danger, vendorsSuccess as success, vendorsFmtDate as fmtDate } from 'utils/config.js';
import './index.less';
import zhCN from 'rc-calendar/lib/locale/zh_CN';
import enUS from 'rc-calendar/lib/locale/en_US';
import DatePicker from 'bee-datepicker';
import Switch from 'bee-switch';
import moment from 'moment';
moment.locale('zh-cn');
import PersonnelEnterpriseModalContent from "./PersonnelEnterPriseModalContent.jsx";

export default class WorkEditFileItem extends Component {
	constructor (props){
		super(props);
		this.state = {
			code: '',
			name: '',
			startDate: '',
			endDate: '',
			description: '',
			manager: '',
			checked: false,
			showModal: false,
			contentType: 'normal',
			saveItem: {},
			modalSize: 'sm',
			modalTitle: '',
			managerData: [],
			managerRec: {},
			handlerModalCancel: null,
			handlerModalConfirm: null,
			enterpriseListData: [],
			enterpriseRole: '10',
			enterpriseRoleArray: [],
			enterpriseItem: null,
			userName: '',
			snameDanger: false,
			scodeDanger: false,
			approvalDateDanger: false,
			enterpriseDivIndex: 0,
			membersData: null,
			insertEnterpriseVOs: [],
			updateEnterpriseVOs: [],
			delPkTeamEnt: [],
			insertMemberVOs: [],
			delPkTeamMember: [],
			pkProject: '',
			changeFlag: '',
			pkTenant: '',
			managerName: '',
			ncStatus: false,
			pkSrc: '',
			projectTypeName: '',
			projectStatusName: '',
			projectState:'',
			orgName:'',
			procedure: [],
			procedureList: [],
			procedureValue: [],
			mapModalShow: false,
			curLocation: {},
			workstopdays: '', // 累计停工天数
			preworkresumeDate: '', // 预计复工日期，
			isUseNewTeam : false,
			enterpriseItems:[],
			enterpriseRoleS : []
		}
	}
	componentDidMount () {
		this.getUseNewTeam(); 
		
	}

	getUseNewTeam = () =>{
		let _me = this;
		
		getUseNewTeamReq({}).then((res)=>{
			if (res.data.resultCode !== "busi_ex") {
				_me.setState({
					isUseNewTeam: res.data.result
				}, ()=>{
					this.getUserBaseData();

					if(window.location.href.indexOf('?') !== -1){
						let urlTag = window.location.href.split('?')[1];
						let searchArray = urlTag.split('&');
						searchArray.forEach((item, index)=>{
							let searchKey = item.split('=')[0];
							let searchValue = item.split('=')[1];
							if(searchKey === 'pkSrc'){
								this.initFromNc(searchValue);
								this.getProcedures();
								this.setState({
									ncStatus: true
								})
							}
						})
					}else{

						this.init();
					}
				});
			}
		}).catch((error)=>{
		})
			
	}

	init = ()=>{
		let pkProject = sessionStorage.getItem('filePkproject');
		searchItemWorkFileList({'id': pkProject, 'isAjax': 1, 'ieStamp': new Date().getTime()},
			res=>{
				let data = res.data.result;
                if(data.teamEnterpriseViewVOs){
					data.teamEnterpriseViewVOs.forEach((item, index)=>{
						item['defaultEntName'] = item['enterpriseName'];
						this.state.enterpriseRoleArray.push(String(item.entRole));
						if(item.teamMemberViewVOs){
							item.teamMemberViewVOs.forEach((item)=>{
								item['userEmail'] = item['email'];
								item['userMobile'] = item['phoneNo'];
								item['key'] = item['userId'] || item["pkUser"];
							})
						}else{
							item.teamMemberViewVOs = []
						}
					})
				}else {
					data.teamEnterpriseViewVOs = []
				}
				this.setState({
					workstopdays: data.workstopdays,
					preworkresumeDate: data.preworkresumeDate,
					startDate: data.approvalDate,
					name: data.sname,
					code: data.scode,
					endDate: data.endDate,
					description: data.description,
					checked: data.iskey,
					manager: data.manager,
					managerName: data.managerName,
					enterpriseListData: data.teamEnterpriseViewVOs,
					pkProject: pkProject,
					changeFlag: data.changeFlag,
					pkTenant: data.pkTenant,
					creationtime: data.creationtime,
					pkSrc: data.pkSrc,
					projectTypeName: data.projectTypeName,
					projectStatusName: data.projectStatusName,
					projectState: this.getProjectState(data.projectState),
					userName: data.creatorName === null? '': data.creatorName,
					orgName: data.orgName,
					procedure: data.procedure||[],
					procedureValue: data.procedure&&data.procedure.map(cur=>cur.pkProcedure),
					curLocation: {
                        lng: data.longitude,
                        lat: data.latitude,
                        address: data.address,
					},
				});
				sessionStorage.setItem('oldEnterpriseKey', data.managerEnt)
			},
			error=>{}
		)
	}
	initFromNc = (pkSrc)=>{
		searchPkFromNc({'pkSrc': pkSrc, 'isAjax': 1},
			res=>{
				let data = res.data.result;
				if(data.teamEnterpriseViewVOs){
					data.teamEnterpriseViewVOs.forEach((item, index)=>{
						item['defaultEntName'] = item['enterpriseName'];
						this.state.enterpriseRoleArray.push(String(item.entRole));
						if(item.teamMemberViewVOs){
							item.teamMemberViewVOs.forEach((item)=>{
								item['userEmail'] = item['email'];
								item['userMobile'] = item['phoneNo'];
							    item['key'] = item['userId'] || item['pkUser'];
							})
						}else{
							item.teamMemberViewVOs = []
						}
					})
				}else {
					data.teamEnterpriseViewVOs = []
				}
				this.setState({
					startDate: data.approvalDate,
					name: data.sname,
					code: data.scode,
					endDate: data.endDate,
					description: data.description,
					checked: data.iskey,
					manager: data.manager,
					managerName: data.managerName,
					enterpriseListData: data.teamEnterpriseViewVOs,
					pkProject: data.pkProject,
					changeFlag: data.changeFlag,
					pkTenant: data.pkTenant,
					creationtime: data.creationtime,
					pkSrc: data.pkSrc,
					projectTypeName: data.projectTypeName,
					projectStatusName: data.projectStatusName,
                    projectState: data.projectState,
					userName: data.creatorName === null? '': data.creatorName,
					orgName: data.orgName,
					procedure: data.procedure||[],
					procedureValue: data.procedure&&data.procedure.map(cur=>cur.pkProcedure),
					curLocation: {
                        lng: data.longitude,
                        lat: data.latitude,
                        address: data.address,
                    },
				});
				sessionStorage.setItem('oldEnterpriseKey', data.managerEnt)
			},
			error=>{}
		)
	}
	getUserBaseData = () => {
		let _me = this;
		//getUserBaseDataUrl({'isAjax': 1, 'ieStamp': new Date().getTime()},
		//	res=>{
		//		if (res.data.result !== null) {
		//			_me.setState({
		//				userName: res.data.result.userName
		//			});
		//		} else {
		//			_me.setState({
		//				userName: ''
		//			});
		//		}
		//	},
		//	error=>{}
		//	)
	}
	getProcedures = ()=>{
		let _me = this;
		searchWorkProList({ 'isAjax': 1, 'ieStamp': new Date().getTime(), status: 1 })
		.then(function(res){
			if (res.data.resultCode != 'busi_ex') {
				if(res.data.result.length !== 0){
					let data = res.data.result;
					data&&data.forEach(cur=>{
						cur.key = cur.pkProcedure;
						cur.title = cur.scode+ ' ' +cur.sname;
						cur.value = cur.pkProcedure;
					})
					_me.setState({
						procedureList: data
					});
				}
			} else {
				danger({'text': res.data.exMsg})
			}
		})
	}
	getColumns = (type) => {
		let _me = this;
		return [
		 	{ title: "姓名", dataIndex: "userName", className: 'text-overflow', key: "userName", width: '20%' },
		    { title: "电话", dataIndex: "userMobile", className: 'text-overflow', key: "userMobile", width: '40%'},
		    { title: "邮箱", dataIndex: "userEmail", key: "userEmail", width: '20%' },
		    { title: "", dataIndex: "y", key: "y", width: '20%',
			      render (text,rec,index) {
			      	return <div className="table-operation">
						{ _me.state.ncStatus && <a href="javascript:;" onClick={_me.handlerDeleteMember(index)}>删除</a>}
			      	</div>
			      }
				}
	   ]
	}
	handlerDeleteMember = (index)=>()=>{
		setTimeout(()=>{
			let delPkTeamMember = this.state.delPkTeamMember;
			let insertMemberVOs = this.state.insertMemberVOs;
			let deleteMemberItem = this.state.enterpriseListData[this.state.enterpriseDivIndex].teamMemberViewVOs[index];
			if(deleteMemberItem.userRole === 0 || deleteMemberItem.pkUser === this.state.manager) {
				danger({text: '项目经理不可删除！'})
				return;
			}
			insertMemberVOs.forEach((item, index)=>{
				if (item['userName'] == deleteMemberItem.userName && item['userRole'] == deleteMemberItem.userRole) {
					insertMemberVOs.splice(index, 1);
				}
			})
			delPkTeamMember.push(deleteMemberItem);
			this.state.enterpriseListData[this.state.enterpriseDivIndex].teamMemberViewVOs.splice(index, 1);
			this.setState({
				enterpriseListData: this.state.enterpriseListData,
				delPkTeamMember,
				insertMemberVOs
			});
		},0)
	}
	getCompnents = (type = 'normal')=>{
		switch (type) {
			case 'normal':
				return '取消后本次所填信息将会丢失！请确认';
				break;
			case 'enterprise':
				return <EnterpriseModalContent saveEnterpriseItem={this.handlerSaveEnterpriseItem} saveEnterpriseRole={this.handlerSaveEnterpriseRole}/>;
				break;
			case 'organize':
				return <MemberModalContent isUseNewTeam = {this.state.isUseNewTeam} data = {this.state.membersData} saveMemberItem={this.handlerSaveMemberItem} hasChooseMemberData={this.state.enterpriseListData[this.state.enterpriseDivIndex].teamMemberViewVOs}/>;
				break;
			case 'managerModal':
				return <ManagerModalContent isUseNewTeam = {this.state.isUseNewTeam} data={this.state.managerData} saveManagerRecord={this.handlerSaveMangerRecord}/>;
				break;
			case 'enterpriseDelete':
				return '确定是否删除这条信息？'
				break;
			case 'personnelenterprise':
				return <PersonnelEnterpriseModalContent pkOrgs ={this.state.pkSrc} saveEnterpriseItem={this.handlerSaveEnterpriseItem} saveEnterpriseRole={this.handlerSaveEnterpriseRole} defaultChooseEnterprise = {this.state.enterpriseListData}/>;
				break;
		}
	}
	handlerSaveMemberItem=(item)=>{
		item.map((memberItem)=>{
			if(this.state.isUseNewTeam){
				memberItem["userEmail"] = memberItem.email;
				memberItem["userMobile"] = memberItem.phone;
				memberItem["userName"] = memberItem.sname
			}else{
				memberItem["userEmail"] = memberItem.userEmail;
				memberItem["userMobile"] = memberItem.userMobile;
				memberItem["userName"] = memberItem.userName
			}
		})
		this.setState({
			memberArray: item
		});
	}
	handlerMemberConfirm = ()=>{
		let newObj = {};
		let insertMemberVOs = this.state.insertMemberVOs;
		let playData = this.state.enterpriseListData[this.state.enterpriseDivIndex].teamMemberViewVOs;
		insertMemberVOs.push(...this.state.memberArray)
		playData.push(...this.state.memberArray);
		playData.forEach((item)=>{
			if (item['userRole'] !== "0"|| item['userRole'] !== 0 || item['pkUser'] !== this.state.manager) {
				item['userRole'] = this.state.enterpriseRole;
			}
			item['pkUser'] = item.pkUser|| item.userId|| item.pkPersonnel
		})
		for(let i =0; i< playData.length;i++){
			if(newObj[playData[i]['userName']]){
				newObj[playData[i]['userName']] ++
				playData.splice(i, 1);
				i--;
			}else{
				newObj[playData[i]['userName']] = 1;
			}
		}
		this.setState({
			enterpriseListData: this.state.enterpriseListData,
			showModal: false,
			insertMemberVOs
		});
	}
	handlerSaveEnterpriseItem = (item) => {
		if(this.state.isUseNewTeam){

			this.setState({
				enterpriseItems: item
			});
		}else{
			this.setState({
				enterpriseItem: item 
			});
		}
	}
	handlerSaveEnterpriseRole = (item) => {
		if(this.state.isUseNewTeam){
			this.setState({
				enterpriseRoleS: item
			});
		}else{
			this.setState({
				enterpriseRole: item
			});
		}
	}
	onChange = (d) => {
	}
	onStartSelect = (date)=>{
		if(date !== null){
			this.setState({
				startDate: new Date(date._d).getTime()
			});
		}
	}
	onEndSelect = (date)=>{
		if(date !== null){
			this.setState({
				endDate: new Date(date._d).getTime()
			});
		}
	}
	handlerSaveCode = (e) => {
		let value = e.target.value;
		let regCode= /[^a-zA-Z0-9\_-]+/img;
		value = value.replace(regCode, '');
		if(value.length >= 20){
			value = value.substring(0, 20);
		}
		this.setState({
			code: value
		});
	}
	handlerSaveName = (e) => {
		let value = e.target.value;
		if(value.length >= 50){
			value = value.substring(0, 50);
		}
		this.setState({
			name: value
		});
	}
	handlerSaveDescription = (e) => {
		let value = e.target.value;
		if(value.length >= 300){
			value = value.substring(0, 300);
		}
		this.setState({
			description: value
		});
	}
	handlerSwitchChoose = () =>{
		this.setState({
			checked: !this.state.checked
		});
	}
	onhide = () => {
		this.setState({
			showModal: false
		});
	}
	handlerDeleteClose = () => {
		this.setState({
			showModal: false
		});
	}
	handlerDeleteConfirm = () => {
		this.setState({
			showModal: false
		});
	}
	handlerCreateEnterprise = ()=>{
		this.setState({
			showModal: true,
			contentType:this.state.isUseNewTeam? "personnelenterprise": 'enterprise',
			modalTitle: '添加企业',
			modalSize: 'lg',
			handlerModalCancel: this.onhide,
			handlerModalConfirm: this.state.isUseNewTeam ? this.handlerSaveEnterpriseS : this.handlerSaveEnterprise ,
			enterpriseItem: null,
			enterpriseRole:  '10',
            enterpriseRoleS:[],
			enterpriseItems: []
		})

	}
	handlerSaveEnterprise = () =>{
		if(this.state.enterpriseItem === null) return;
		let enterpriseArray = this.state.enterpriseListData;
		let insertEnterpriseVOs = this.state.insertEnterpriseVOs;
		let isHasSameEnterprise = false;
		this.state.enterpriseRoleArray.push(String(this.state.enterpriseRole));
		enterpriseArray.forEach((item, index)=>{
			if(item.defaultEntName === this.state.enterpriseItem.name){
				danger({'text': '已经选择了该企业！'});
				isHasSameEnterprise = true;
			}
		})
		if(isHasSameEnterprise) return;
		enterpriseArray.push({
			pkEnterprise: this.state.enterpriseItem.id,
			entRole: this.state.enterpriseRole,
			defaultEntName: this.state.enterpriseItem.name,
			teamMemberViewVOs: []
		});
		insertEnterpriseVOs.push({
			pkEnterprise: this.state.enterpriseItem.id,
			entRole: this.state.enterpriseRole,
			defaultEntName: this.state.enterpriseItem.name,
			teamMemberViewVOs: []
		});
		this.setState({
			showModal: false,
			enterpriseListData: enterpriseArray,
			enterpriseRoleArray: this.state.enterpriseRoleArray,
			insertEnterpriseVOs
		});
	}


		//使用新版本的团队功能，保存企业
		handlerSaveEnterpriseS = () =>{
			if(!this.state.enterpriseItems.length) return;
			let enterpriseArray = this.state.enterpriseListData;
			let insertEnterpriseVOs = this.state.insertEnterpriseVOs;
			let isHasSameEnterprise = false;
			this.state.enterpriseRoleArray.concat(this.state.enterpriseRoleS);
			
			enterpriseArray.forEach((item, index)=>{
				this.state.enterpriseItems.find((enterpriseItem)=>{
					if(item.defaultEntName === enterpriseItem.name || item.pkEnterprise === enterpriseItem.pkEnterprise){
						danger({'text': `已经选择[${enterpriseItem.name}]企业！`});
						isHasSameEnterprise = true;
					}
				})
				
			})
			if(isHasSameEnterprise) return;
	
	
			
			this.state.enterpriseItems.map((item,index)=>{
				enterpriseArray.push({
					pkEnterprise: item.pkEnterprise,
					entRole:item.role ? item.role.toString() :item.entRole.toString(),
					defaultEntName: item.name,
					teamMemberViewVOs: []
				});
				insertEnterpriseVOs.push({
					pkEnterprise: item.pkEnterprise,
					entRole:item.role ? item.role.toString() :item.entRole.toString(),
					defaultEntName: item.name,
					teamMemberViewVOs: []
				});
				this.state.enterpriseRoleArray.push(item.role ? item.role.toString() :item.entRole.toString())
			})
			
			this.setState({
				showModal: false,
				enterpriseListData: enterpriseArray,
				enterpriseRoleArray: this.state.enterpriseRoleArray,
				insertEnterpriseVOs
			});
		}

	handlerSaveItem = () => {
		let project = Object.assign({},	{sname: this.state.name},
									  	{approvalDate: this.state.startDate},
									  	{endDate: this.state.endDate},
									  	{scode: this.state.code},
									  	{iskey: this.state.checked},
									  	{description: this.state.description},
									  	{manager: this.state.manager},
									  	{pkProject: this.state.pkProject},
										{changeFlag: this.state.changeFlag},
										{procedures: this.state.procedureValue},
										{address: this.state.curLocation.address},
									    {longitude: this.state.curLocation.lng},
									    {latitude: this.state.curLocation.lat},
									  	{pkTenant: this.state.pkTenant});

	  	let enterpriseUpdateInfo = {
	  		insertEnterpriseVOs: this.state.insertEnterpriseVOs,
	  		updateEnterpriseVOs: this.state.updateEnterpriseVOs,
	  		deleteEnterpriseVOs: this.state.delPkTeamEnt
	  	};
	  	let memberUpdateInfo = {
	  		insertMemberVOs: this.state.insertMemberVOs,
	  		updateMemberVOs: [],
	  		deleteMemberVOs: this.state.delPkTeamMember
	  	};
		let param = Object.assign({}, {project}, {enterpriseUpdateInfo}, {memberUpdateInfo});
		editWorkFileList(param,
		 res=>{
			 if(res.data.resultCode !== 'busi_ex'){
		 			success({text: '保存成功！'});
		 			let data = res.data.result;
					if(data.teamEnterpriseViewVOs){
						data.teamEnterpriseViewVOs.forEach((item, index)=>{
							item['defaultEntName'] = item['enterpriseName'];
							this.state.enterpriseRoleArray.push(String(item.entRole));
							if(item.teamMemberViewVOs){
								item.teamMemberViewVOs.forEach((item)=>{
									item['userEmail'] = item['email'];
									item['userMobile'] = item['phoneNo'];
									item['key'] = item['userId'];
								})
							}else{
								item.teamMemberViewVOs = []
							}
						})
					}else {
						data.teamEnterpriseViewVOs = []
					}
					this.setState({
						startDate: data.approvalDate,
						name: data.sname,
						code: data.scode,
						endDate: data.endDate,
						description: data.description,
						checked: data.iskey,
						manager: data.manager,
						managerName: data.managerName,
						enterpriseListData: data.teamEnterpriseViewVOs,
						pkProject: data.pkProject,
						changeFlag: data.changeFlag,
						pkTenant: data.pkTenant,
						creationtime: data.creationtime,
						projectState: data.projectState,
						insertMemberVOs: [],
						delPkTeamMember :[],
						insertEnterpriseVOs:[],
						updateEnterpriseVOs: [],
						delPkTeamEnt: [],
					});
		 		}else{
		 			danger({text: res.data.exMsg});
		 		}
		 },
		 error=>{}
	 	);
	}
	handlerSetBorderStatus = (data) => {
		for (let name in data) {
			if (data[name] === '') {
				switch(name){
					case 'sname':
					this.setState({
						snameDanger: true
					});
					break;
					case 'scode':
					this.setState({
						scodeDanger: true
					});
					break;
					case 'approvalDate':
					this.setState({
						approvalDateDanger: true
					});
					break;
				}
			} else {
				switch(name){
					case 'sname':
					this.setState({
						snameDanger: false
					});
					break;
					case 'scode':
					this.setState({
						scodeDanger: false
					});
					break;
					case 'approvalDate':
					this.setState({
						approvalDateDanger: false
					});
					break;
				}
			}
		}
	}

	handlerShowManagerModal = () => {
		getManagerList({},
			res=>{
				let data = res.data.result;
				data.content.forEach((item, idnex)=>{
					item['key'] = item['userId'];
				})
				this.setState({
					showModal: true,
					contentType: 'managerModal',
					modalSize: 'lg',
					modalTitle: '项目经理',
					managerData: data.content,
					handlerModalCancel: this.onhide,
					handlerModalConfirm: this.handlerSaveManager
				});
			},
			error=>{}
		)
	}
	handlerSaveManager = () =>{
		let delPkTeamEnt = this.state.delPkTeamEnt;
		let delPkTeamMember = this.state.delPkTeamMember;
		let insertMemberVOs = this.state.insertMemberVOs;
		let enterpriseArray = this.state.enterpriseListData;
		let insertEnterpriseVOs = this.state.insertEnterpriseVOs;
		let oldEnterpriseKey = sessionStorage.getItem('oldEnterpriseKey');
		this.state.managerRec['teamMemberViewVOs'] = [{
			userName: this.state.managerRec.userName,
			userMobile: this.state.managerRec.userMobile,
			userEmail: this.state.managerRec.userEmail,
			pkUser: this.state.managerRec.userId,
			pkEnterprise: this.state.managerRec.defaultEntId,
			userRole: !this.state.isUseNewTeam ? 0 :  this.state.managerRec.defaultRole, 
		}];
		insertMemberVOs.push({
			userName: this.state.managerRec.userName,
			userMobile: this.state.managerRec.userMobile,
			userEmail: this.state.managerRec.userEmail,
			pkUser: this.state.managerRec.userId,
			pkEnterprise: this.state.managerRec.defaultEntId,
			userRole:!this.state.isUseNewTeam ? 0 :  this.state.managerRec.defaultRole, 
		});
		let newRec = Object.assign({}, this.state.managerRec, {entRole:  !this.state.isUseNewTeam  ? '10' : this.state.managerRec.defaultRole });
		enterpriseArray.push(newRec);
		insertEnterpriseVOs.push(newRec)
		this.state.enterpriseRoleArray.push('10');
		if(oldEnterpriseKey){
			enterpriseArray.forEach((item, index)=>{
				if(item.pkEnterprise === oldEnterpriseKey){
					if(enterpriseArray[index].teamMemberViewVOs.length === 1){
						let deleteEnt = enterpriseArray.splice(index, 1);
						delPkTeamEnt.push(deleteEnt[0])
						this.state.enterpriseRoleArray.splice(index, 1);
					}else{
						enterpriseArray[index].teamMemberViewVOs.forEach((item, innerIndex)=>{
							if(item['userRole'] === 0|| item['pkUser'] === this.state.manager) {
								let deleteMem = enterpriseArray[index].teamMemberViewVOs.splice(innerIndex, 1);
								delPkTeamMember.push(deleteMem[0])
							}
						})
					}
				}
			})
		}
		sessionStorage.setItem('oldEnterpriseKey', this.state.managerRec.pkEnterprise)
		this.setState({
			showModal: false,
			enterpriseListData: enterpriseArray,
			managerName: this.state.managerRec.userName,
			manager: this.state.managerRec.userId,
			enterpriseRoleArray: this.state.enterpriseRoleArray,
			insertEnterpriseVOs,
			delPkTeamEnt,
			delPkTeamMember,
			insertMemberVOs
		});
	}
	handlerSaveMangerRecord = (item) => {
		this.setState({
			managerRec: Object.assign({}, item, {pkEnterprise: item.defaultEntId})
		});
	}
	handleChange = (value)=>{
        let updateEnterpriseVOs = this.state.updateEnterpriseVOs;
        let currentRowValue = this.state.enterpriseListData[this.state.enterpriseDivIndex];
        let count = 0;
        if(this.state.insertEnterpriseVOs.length>0){
            this.state.insertEnterpriseVOs.forEach((item, index)=>{
                if(currentRowValue.pkEnterprise === item.pkEnterprise){
                    count++;
                    item['entRole'] = value;
                }
            })
        }
        if(this.state.insertMemberVOs.length>0){
            this.state.insertMemberVOs.forEach((item, index)=>{
                if(currentRowValue.pkEnterprise === item.pkEnterprise){

					item['userRole'] = value;
                }
            })
        }
        if(count === 0){
            this.state.enterpriseListData[this.state.enterpriseDivIndex]['entRole'] = value;
            this.state.enterpriseListData[this.state.enterpriseDivIndex]['teamMemberViewVOs'].forEach((item)=>{
                item['userRole'] = value;
            })
            let countUpdate = 0;
            if(updateEnterpriseVOs.length>0){
                updateEnterpriseVOs.forEach((item, index)=>{
                    if(currentRowValue.pkEnterprise === item.pkEnterprise){
                        //item['entRole'] = value;
                        updateEnterpriseVOs.splice(index,1);
                        countUpdate++;//currentRowValue
                        updateEnterpriseVOs.push(this.state.enterpriseListData[this.state.enterpriseDivIndex]);
                    }
                })
            }
            if(countUpdate === 0){
                updateEnterpriseVOs.push(this.state.enterpriseListData[this.state.enterpriseDivIndex]);
            }
        }


        this.state.enterpriseRoleArray[this.state.enterpriseDivIndex] = value;

        this.setState({
            defaultValueRole: value,
            enterpriseRoleArray: this.state.enterpriseRoleArray,
            updateEnterpriseVOs
        })
	}
	handlerCreateMembers = (item, index) => () => {
		let membersData = Object.assign({}, item, {role: this.state.enterpriseRoleArray[index]})
		this.setState({
			showModal: true,
			contentType: 'organize',
			modalSize: 'lg',
			modalTitle: '添加成员',
			membersData,
			handlerModalCancel: this.onhide,
			handlerModalConfirm: this.handlerMemberConfirm
		});
	}
	handlerCancelItem = ()=>{
		this.setState({
			showModal: true,
			contentType: 'normal',
			modalSize: 'sm',
			modalTitle: '',
			handlerModalCancel: this.onhide,
			handlerModalConfirm: this.handlerCancel
		});
	}
	handlerCancel = ()=>{
		window.location.href= "./workfile.html";
	}
	handlerDeleteEnterprise = () => {
		let stop = false;
		let delPkTeamEnt = this.state.delPkTeamEnt;
		let insertEnterpriseVOs = this.state.insertEnterpriseVOs;
		let enterpriseData = this.state.enterpriseListData;
		let enterpriseRoleArray = this.state.enterpriseRoleArray;
		let deleteItem = enterpriseData[this.state.chooseDeleteIndex];
		let deleteEnterpriseItem = enterpriseData[this.state.chooseDeleteIndex];
		deleteEnterpriseItem.teamMemberViewVOs.forEach((item, index)=>{
			if(item.userRole === '0' || item.userRole === 0 || item.pkUser=== this.state.manager){
				danger({text: '存在项目经理的项目不能删除！'});
				stop = true;
			}
			return;
		})
		if(stop) return;
		insertEnterpriseVOs.forEach((item, index)=>{
			if(item['pkEnterprise'] == deleteItem.pkEnterprise){
				insertEnterpriseVOs.splice(index, 1);
			}
		})
		delPkTeamEnt.push(deleteItem)
		enterpriseData.splice(this.state.chooseDeleteIndex, 1);
		enterpriseRoleArray.splice(this.state.chooseDeleteIndex, 1);

		this.setState({
			enterpriseListData: enterpriseData,
			enterpriseRoleArray,
			showModal: false,
			insertEnterpriseVOs
		});
	}
	handlerShowDeleteModal = (index)=>()=>{
		this.setState({
			showModal: true,
			modalSize: 'sm',
			modalTitle: '',
			chooseDeleteIndex: index,
			contentType: 'enterpriseDelete',
			handlerModalCancel: this.onhide,
			handlerModalConfirm: this.handlerDeleteEnterprise
		});
	}
	handlerChooseDivIndex = (index)=>()=>{
		this.setState({
			enterpriseDivIndex: index
		});
	}
	handleReturn = ()=>{
		window.location.href="./workfile.html"
	}
	getProjectState = (state) =>{
        let projectState = '';
        switch (state){
            case -1:
                projectState = '创建';
                break;
            case 0:
                projectState = '施工中';
                break;
            case 1:
                projectState = '竣工';
                break;
            case -2:
                projectState = '暂停';
                break;
        }
       return projectState
	}
	handleProcedureChange = (a) => {
		this.setState({
			procedureValue: a
		})
	}
	mapModalClose = (lng, lat, address) => {
		document.getElementById('app').style.overflow = "auto";

		this.setState({
			mapModalShow: false
		});
		if (lng) {
			this.setState({
				curLocation:{
					lng,
					lat,
					address,
				}
			})
		}
	}
	openMapModal= ()=>{
		document.getElementById('app').style.overflow = "hidden";
		this.setState({
			mapModalShow: true,
		})
	}
	clearPosition=()=>{
		this.setState({
			curLocation:{
			}
		})
	}
	render (){
		let { code,
				orgName,
				name,
				description, 
				checked, 
				showModal, 
				contentType, 
				modalSize, 
				modalTitle, 
				enterpriseListData, 
				managerName, 
				userName, 
				snameDanger, 
				scodeDanger, 
				approvalDateDanger, 
				enterpriseRoleArray, 
				creationtime,
				projectTypeName,
				projectStatusName,
				procedureList,
				procedureValue,
				ncStatus,
				workstopdays,
				preworkresumeDate
			} = this.state;
		return (
			<App>
				<CommonModal show={showModal}
		                        cancel={this.state.handlerModalCancel}
		                        confirm={this.state.handlerModalConfirm}
		                        hide={this.onhide}
		                        backdrop={true}
		                        content={this.getCompnents(contentType)}
		                        size={modalSize}
		                        title={modalTitle}
		                        >
           		</CommonModal>
				<div className="header clearfix">
					{
						!this.state.ncStatus && <div className="bread-crumb">
						<Breadcrumb>
						    <Breadcrumb.Item href="./workfile.html">
						      项目列表
						    </Breadcrumb.Item>
						    <Breadcrumb.Item href="./workfiledetail.html">
						      项目详情
						    </Breadcrumb.Item>
						</Breadcrumb>
					</div>
					}
					<div className="item-user">
						<p>创建人：{userName}</p>
						<p>创建时间：{fmtDate(creationtime)}</p>
					</div>
				</div>
				<div className="basedata--content">
					<div className="base--header clearfix">
						<p>基本信息</p>
						<div className="btn-group">
							{this.state.ncStatus && <Button colors="primary" onClick={this.handlerSaveItem}>保存</Button> }
							{!this.state.ncStatus && <Button colors="primary" onClick={this.handleReturn}>返回</Button> }
						</div>
					</div>
					<div className="base--content">
						<Row>
							<Col md={6} xs={6} sm={6}>
								<div className='base--input__group clearfix'>
									<i className="red--icon">*</i>
									<span className="name">项目编码：</span>
			                    	<FormControl size="lg" disabled={true} placeholder="20个数字、英文以内" onChange={this.handlerSaveCode} value={code} className={ scodeDanger ? 'danger-boder': ''}/>
			                    	{ scodeDanger ? <b className="notice--tip">内容不能为空</b> : ''}
								</div>
			                </Col>
			                <Col md={6} xs={6} sm={6}>
			                    <div className='base--input__group clearfix'>
			                    	<i className="red--icon">*</i>
									<span className="name">项目名称：</span>
			                    	<FormControl size="lg" disabled={true}  placeholder="50个汉字、英文、数字、符号以内" onChange={this.handlerSaveName} value={name} className={ snameDanger? 'danger-boder': ''} />
			                    	{ snameDanger ? <b className="notice--tip">内容不能为空</b> : ''}
								</div>
			                </Col>
			                <Col md={6} xs={6} sm={6}>
			                    <div className='base--input__group clearfix'>
									<span className="name">项目经理：</span>
			                    	<FormControl size="lg" disabled={true}  placeholder={'请点击选择！'} onClick={this.handlerShowManagerModal} value={managerName}/>
								</div>
			                </Col>
			                <Col md={6} xs={6} sm={6}>
								<div className='base--input__group clearfix'>
									<i className="red--icon">*</i>
									<span className="name">项目状态：</span>
									{this.state.projectStatusName?
										<FormControl size="lg" disabled={true} value={this.state.projectStatusName}/> :
										<Select className='base--input__dropInput '
											value={this.state.projectState}
											disabled
										// onSelect={this.handleDropSearch}
									>
										<Select.Option value="-1">创建 </Select.Option>
										<Select.Option value="0">施工中</Select.Option>
										<Select.Option value="1">竣工</Select.Option>
										<Select.Option value="-2">暂停 </Select.Option>
									</Select>}
								</div>
			                </Col>
							<Col md={6} xs={6} sm={6}>
								<div className='base--input__group clearfix'>
									<span className="name">累计停工天数(天)：</span>
									<FormControl size="lg" disabled={true} value={workstopdays}/>
								</div>
			                </Col>
							<Col md={6} xs={6} sm={6}>
								<div className='base--input__group clearfix'>
									<span className="name">预计复工日期：</span>
									<FormControl size="lg" disabled={true} value={preworkresumeDate}/>
								</div>
			                </Col>
			                <Col md={6} xs={6} sm={6}>
			                    <div className='base--input__group clearfix'>
			                    	<i className="red--icon">*</i>
									<span className="name">立项日期：</span>
			                    	<DatePicker
			                            format={"YYYY-MM-DD"}
			                            onSelect={this.onStartSelect}
			                            onChange={this.onChange}
			                            locale={zhCN}
			                            disabled={true} 
			                            placeholder = {'选择日期时间'}
			                            value={moment(this.state.startDate)}
			                            className={ approvalDateDanger ? 'danger-boder': ''}
			                        />
			                        { approvalDateDanger ? <b className="notice--tip">内容不能为空</b> : ''}
								</div>
			                </Col>
			                <Col md={6} xs={6} sm={6}>
								<div className='base--input__group clearfix'>
									<span className="name">重点项目：</span>
									<div className='switch--containers'>
										<Switch checked={checked} disabled={true} onChange={this.handlerSwitchChoose}/>
									</div>
                                    {
                                        this.state.endDate?
                                        <div className='base--input__closeTime'>
                                            <span>验收日期:</span>
                                            <span style={{marginLeft:'6px'}}>{fmtDate(this.state.endDate)}</span>
                                        </div> :
                                        null
                                    }

								</div>
			                </Col>
							<Col md={6} xs={6} sm={6}>
								<div className='base--input__group clearfix'>
									<span className="name">项目组织：</span>
									<FormControl size="lg" disabled={true} placeholder=""  value={orgName} className={ scodeDanger ? 'danger-boder': ''}/>

								</div>
							</Col>
							{
								this.state.pkSrc !== null && <div>
											<Col md={6} xs={6} sm={6}>
												<div className='base--input__group clearfix'>
													<span className="name">项目类型：</span>
													<span className="projectKey">{projectTypeName}</span>
												</div>
							                </Col>
							                {/*<Col md={6} xs={6} sm={6}>
							                    <div className='base--input__group clearfix'>
													<span className="name">项目状态：</span>
													<span className="projectKey">{projectStatusName}</span>
												</div>
							                </Col>*/}
						                </div>
							}
						</Row>
						<Row>
							<Col md={6} xs={6} sm={6}>
								<div className='base--input__group clearfix base--input__groupMutiSelect'>
									<span className="name">适用工序：</span>
									<Select
										multiple
										disabled={ncStatus ? false : true}
										className={'base--input__MultiSelect'}
										onChange={this.handleProcedureChange}
										placeholder={ncStatus ? '请点击选择工序' : ''}
										value={ncStatus ? (procedureValue || []) : this.state.procedure.map(cur => cur.pkProcedure)}
										dropdownMatchSelectWidth
										showSearch
										notFoundContent="没有相关条目"
										optionFilterProp="value"
									// size = "lg"
									>
										{ncStatus ?
											procedureList.map(cur => {
												return <Select.Option key={cur.pkProcedure}>{cur.scode + ' ' + cur.sname}</Select.Option>
											})
											:
											this.state.procedure.map(cur => <Select.Option key={cur.pkProcedure}>
												{cur.scode + ' ' + cur.sname}
											</Select.Option>)
										}
									</Select>
								</div>
							</Col>
							<Col md={6} xs={6} sm={6}>
								{
									ncStatus ?
										<div className='base--input__group clearfix'>
											<span className="name">项目地址：</span>
											<a href="javascript:;" className='refer-map' onClick={this.openMapModal}>关联地图</a>
											<FormControl className='map-text' size="lg" disabled value={this.state.curLocation.address || ''} />
											<i className="clear-position-icon" onClick = {this.clearPosition}></i>
										</div>
										:
										<div className='base--input__group clearfix'>
											<span className="name">项目地址：</span>
											<FormControl size="lg" disabled value={this.state.curLocation.address || ''} />
										</div>
								}
							</Col>
			                <Col md={12} xs={12} sm={12}>
			                    <div className='base--input__group clearfix'>
									<span className="name">项目描述：</span>
			                    	<textarea size="lg" disabled={true} placeholder={'请输入'} value={this.state.description} onChange={this.handlerSaveDescription}/>
								</div>
			                </Col>

						</Row>
					</div>
				</div>
				<div className="enterprise--basedata">
					<div className="enterprise--header clearfix">
						<p>企业和团队</p>
						{
							this.state.ncStatus && <a href="javascript:;" onClick={this.handlerCreateEnterprise}>
														添加企业
														<i className="enterprise--icon"></i>
													</a>
						}
					</div>
					{ enterpriseListData.length !== 0 && 
						enterpriseListData.map((item, index)=>{
							return <div className="enterprise--content" onClick={this.handlerChooseDivIndex(index)}>
										<div className="enterprise--item">
											<div className="item--header">
												<Row>
													<Col md={2} xs={2} sm={2}>
														{this.state.isUseNewTeam ? 
															 <Select
																size="lg"
																style={{width: 150, marginLeft: 24, marginTop: 8}}
																onChange={this.handleChange}
																placeholder={'请选择'}
																value={enterpriseRoleArray[index]}
																disabled = {this.state.isUseNewTeam}//现规则， 一个租户下的一个企业只可以有一个角色，不允许修改了
															>
																<Option value="10">业主方</Option>
																<Option value="20">施工方</Option>
																<Option value="30">监理方</Option>
																<Option value="40">设计方</Option>
																<Option value="50">客户方</Option>
															
															</Select>
															:

															<Select
																size="lg"
																style={{ width: 150, marginLeft: 24, marginTop: 8}}
																onChange={this.handleChange}
																placeholder={'请选择'}
																disabled={!this.state.ncStatus ? true : false}
																value={enterpriseRoleArray[index]}
																>
																<Option value="10">业主方</Option>
																<Option value="20">施工方</Option>
																<Option value="30">监理方</Option>
															</Select>
														}
														
													</Col>
													<Col md={10} xs={10} sm={10} className="clearfix">
														<p>{item.defaultEntName}</p>
														{
															this.state.ncStatus && <a href="javascript:;" onClick={this.handlerShowDeleteModal(index)}>删除</a>
														}
													</Col>
												</Row>
											</div>
											<div className="item--content">
												<Row>
													<Col md={2} xs={2} sm={2}>
														<p>团队成员</p>
													</Col>
													<Col md={10} xs={10} sm={10}>
														{
															this.state.ncStatus && <a href="javascript:;" className="btn--add__member" onClick={this.handlerCreateMembers(item, index)}>
																						添加成员
																						<i className="member--icon"></i>
																					</a>
														}
														<Table data={item.teamMemberViewVOs} columns={this.getColumns()}></Table>
													</Col>
												</Row>
											</div>
										</div>
									</div>
						})
					 }
				</div>
				<MapModal
					show={this.state.mapModalShow}
					onClose={this.mapModalClose}
					initLocation={this.state.curLocation}
					from={'detail'}
				/>
			</App>
			)
	}
}